import { Edge, Node } from "@antv/x6";
import { nodeSize } from "./nodePoint";

// 根据节点ID获取关联边
const getNodeEdges = (graph: { getEdges: () => any[] }, nodeId: string) => {
  return graph
    .getEdges()
    .filter(
      (edge: {
        getSource: () => { (): any; new (): any; cell: any };
        getTarget: () => { (): any; new (): any; cell: any };
      }) => edge.getSource().cell === nodeId || edge.getTarget().cell === nodeId
    );
};

/**
 * 获取节点详情
 * @param { Element }  elementGraph antv x6 元素
 * @param { Node }  node 节点元素
 * @param { _ref }  _ref 弹窗
 */
const getNodesDetail = (elementGraph: any, node: Node, _ref: any) => {
  if (!["node-point"].includes(node.shape)) return;
  node.toBack();
  const nData = node.getData();
  const tempEdgeName = getNodeEdges(elementGraph, node.id)
    .map((item: any) => item.id)
    .join(",");
  const params = {
    ...nData,
    shape: node.shape,
    tempEdgeName,
  };
  _ref.showDialog(true, params);
  elementGraph.resetSelection();
};

/**
 * 获取边详情
 * @param { Element }  elementGraph antv x6 元素
 * @param { Edge }  edge 边元素
 * @param { _ref }  _ref 弹窗
 */
const getEdgesDetail = (elementGraph: any, edge: Edge, _ref: any) => {
  if (!["edge"].includes(edge.shape)) return;
  edge.toBack();
  const eData = edge.getData();
  // 获取边的长度
  let lengths: number = 0;
  const view = elementGraph.findViewByCell(edge);
  const lengthFloor: number = view?.path?.length();
  lengths = Math.floor(lengthFloor * 100) / 100;
  const params = {
    ...eData,
    shape: edge.shape,
    lengths,
    sourceX: edge.getSourcePoint().x - nodeSize / 2,
    sourceY: edge.getSourcePoint().y - nodeSize / 2,
    targetX: edge.getTargetPoint().x - nodeSize / 2,
    targetY: edge.getTargetPoint().y - nodeSize / 2,
  };
  _ref.showDialog(true, params);
  elementGraph.resetSelection();
};

/**
 * 获取区域详情
 * @param { Element }  elementGraph antv x6 元素
 * @param { Node }  node 边节点素
 * @param { _ref }  _ref 弹窗
 */
const getAreaDetail = (elementGraph: any, node: Node, _ref: any) => {
  if (!["node-area"].includes(node.shape)) return;
  node.toBack();
  const aData = node.getData();
  const areaCoordinates = aData.points.map((item: { x: number; y: number }) => `(${item.x}, ${item.y})`).join(",");
  const params = {
    ...aData,
    shape: node.shape,
    zoneNameEn: aData.zoneNameEn,
    zoneName: aData.zoneName,
    zoneFunction: aData.zoneFunction,
    areaCoordinates,
  };
  _ref.showDialog(true, params, node);
  elementGraph.resetSelection();
};

export { getNodesDetail, getEdgesDetail, getAreaDetail };
